package cn.usts.edu.ReflectionGetAndSetAnnotation;


import java.lang.annotation.*;
import java.lang.reflect.Field;

/**
 * @author ：fly
 * @description: 利用反射操作注解
 * @date ：2021/10/29 15:36
 */
public class GetSetAnnotation {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        // 通过反射获取对象
        Class<?> u1 = Class.forName("cn.usts.edu.ReflectionGetAndSetAnnotation.User");

        // 通过反射对象获取注解
        Annotation[] annotations = u1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //   获取注解对象                                         注解名子.class
        testAnnotation1 testAnnotation1 =u1.getAnnotation(testAnnotation1.class);
        // 获取注解的value         注解对象.属性()
        System.out.println(testAnnotation1.tableName());

        // 获取指定属性
        Field age = u1.getDeclaredField("age");
        // 指定属性上的注解
        testFiledAnnotation ageAnnotation = age.getAnnotation(testFiledAnnotation.class);
        System.out.println("columnName-->"+ageAnnotation.columnName());
        System.out.println("type-->"+ageAnnotation.type());
        System.out.println("length-->"+ageAnnotation.length());
    }


}

@testAnnotation1(tableName = "tb_User")
class User{
    @testFiledAnnotation(columnName = "User_age",type = "int",length = 10)
    int age;
    @testFiledAnnotation(columnName = "User_name",type = "varChar",length = 20)
    String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User() {
    }

    public User(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

// 类注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface testAnnotation1{
    String tableName();
}

// 属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface testFiledAnnotation{
    String columnName();
    int length();
    String type();
}